package cn.wolfcode.wolf2w.redis.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyStatisVO;
import cn.wolfcode.wolf2w.redis.IStrategyRedisService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.DateUtil;
import cn.wolfcode.wolf2w.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class StrategyRedisServiceImpl implements IStrategyRedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IStrategyService strategyService;

    @Override
    public void ViewnumIncrease(String id, int num) {
        //拼接vo的key
        String key = RedisKeys.STRATEGY_STATIS_VO.join(id);

         //判断vo对象是否存在
        StrategyStatisVO vo=null;
        //判断该key是否存在redis中
        if(redisTemplate.hasKey(key)){
            //如果存在，直接通过这个key获取vo对象
            String voStr = redisTemplate.opsForValue().get(key);
            vo = JSON.parseObject(voStr, StrategyStatisVO.class);
        }else {
              //如果不存在，先初始化，然后当前阅读数+num
            vo = new StrategyStatisVO();
            Strategy strategy = strategyService.get(id);
            //初始化
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());
        }
        vo.setViewnum(vo.getViewnum()+num);
        //更新vo对象
        redisTemplate.opsForValue().set(key,JSON.toJSONString(vo));

    }

    @Override
    public StrategyStatisVO getStringStratisVo(String sid) {
        //拼接vo的key
        String key = RedisKeys.STRATEGY_STATIS_VO.join(sid);

        //判断vo对象是否存在
        StrategyStatisVO vo=null;
        //判断该key是否存在redis中
        if(redisTemplate.hasKey(key)){
            //如果存在，直接通过这个key获取vo对象
            String voStr = redisTemplate.opsForValue().get(key);
            vo = JSON.parseObject(voStr, StrategyStatisVO.class);
        }else {
            //如果不存在，先初始化
            vo = new StrategyStatisVO();
            Strategy strategy = strategyService.get(sid);
            //初始化
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());
            //更新vo对象
            redisTemplate.opsForValue().set(key,JSON.toJSONString(vo));
        }
        //返回vo对象
        return vo;

    }

    @Override
    public void setStringStratisVo(StrategyStatisVO vo) {
        String key = RedisKeys.STRATEGY_STATIS_VO.join(vo.getStrategyId());
        redisTemplate.opsForValue().set(key,JSON.toJSONString(vo));
    }

    @Override
    public void setReplynum(String sid, int num) {
        //先拼接key，判断redis中是否存在key
        String key = RedisKeys.STRATEGY_STATIS_VO.join(sid);
        StrategyStatisVO vo = null;
        if(redisTemplate.hasKey(key)){
            //如果存在，获取vo对象，将评论数加1
            String vostr = redisTemplate.opsForValue().get(key);
            vo = JSON.parseObject(vostr,StrategyStatisVO.class);
            vo.setReplynum(vo.getReplynum()+1);
        }else {
            //如果不存在。先初始化vo对象
            vo = new StrategyStatisVO();
            //获取数据库中当前攻略的数据
            Strategy strategy = strategyService.get(sid);
            //初始化，将当前攻略数据作为源，添加进去vo对应的属性中
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());
            vo.setReplynum(vo.getViewnum()+1);
        }
        //更新vo
        redisTemplate.opsForValue().set(key,JSON.toJSONString(vo));

    }




    @Override
    public Boolean favor(String sid, String uid) {
        //先拼接用户id对应的key
        String key = RedisKeys.STRATEGY_USER_FAVOR.join(uid);
        //判断该key是否存在redis中
        List<String> sidList = new ArrayList<>();
        if(redisTemplate.hasKey(key)){
            // 如果该key存在。则通过key获取对应的list集合
            String sids = redisTemplate.opsForValue().get(key);
            //将字符串转为集合
            sidList =JSON.parseArray(sids,String.class);
        }

        // 判断sidList是否存在该sid，
        StrategyStatisVO vo = this.getStringStratisVo(sid);
        if (sidList.contains(sid)){
            //包含则为取消收藏操作，获取当前vo对象，将收藏数-1，并且将当前攻略id移除list集合
            vo.setFavornum(vo.getFavornum()-1);
            sidList.remove(sid);
        }else{
            //  如果不包含，则为收藏操作，获取当前vo对象，将收藏数+1，添加进list集合中
            vo.setFavornum(vo.getFavornum()+1);
            sidList.add(sid);
        }
        //如果该key不存在，创建一个List集合，初始化到list中
       // 最后，更新list，vo对象
        redisTemplate.opsForValue().set(key,JSON.toJSONString(sidList));
        this.setStringStratisVo(vo);
        return sidList.contains(sid);
    }

    @Override
    public Boolean strategyThumbup(String sid, String uid) {
        //拼接用户顶操作的key实例对象
        String key = RedisKeys.STRATEGY_USER_THUMBUP.join(sid, uid);
        //拼接攻略id的key实例对象
        String strkey = RedisKeys.STRATEGY_STATIS_VO.join(sid);
        //判断key是否存在redis中
        if(!redisTemplate.hasKey(key)){
            //如果不存在，表示今天没有顶过，获取vo对象，顶+1，并将操作记号存入redis中
            StrategyStatisVO vo = this.getStringStratisVo(sid);
            vo.setThumbsupnum(vo.getThumbsupnum()+1);
            //设置有效时间=今天最后一秒-当前时间
            Date date = new Date();
            Date endDate = DateUtil.getEndDate(date);
            long time = DateUtil.getDateBetween(date, endDate);
            //更新对象
            redisTemplate.opsForValue().set(key,"1",time, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(strkey,JSON.toJSONString(vo));
            return true;
        }
        //如果存在，则表示今天已经顶过了，直接放回
        return false;

    }

    @Override
    public List<String> favorView(String sid, String userId) {
        //拼接key
        if(!StringUtils.hasLength(userId)){
                return new ArrayList<>();
        }
        String key = RedisKeys.STRATEGY_USER_FAVOR.join(userId);
        List<String> sidList = new ArrayList<>();
        if(redisTemplate.hasKey(key)){
            //通过key查询对应的sid集合
            String sids = redisTemplate.opsForValue().get(key);
            sidList = JSON.parseArray(sids, String.class);
        }
        return sidList;
    }

    @Override
    public boolean isVoExits(String sid) {
        String key = RedisKeys.STRATEGY_STATIS_VO.join(sid);
        return redisTemplate.hasKey(key);
    }

    @Override
    public List<StrategyStatisVO> queryStrategyRedisByPattern(String s) {
          //拼接key规则查询对应的keys
        String keyPattern = RedisKeys.STRATEGY_STATIS_VO.join(s);
        /*
        * 查询redis中所有vo对象对应的key
        * */
        Set<String> keys = redisTemplate.keys(keyPattern);
        List<StrategyStatisVO> list = new ArrayList<>();
        if(keys !=null && keys.size()>0){
            for (String key : keys) {
                //通过key获取vo对象,存入集合中
                String vostr = redisTemplate.opsForValue().get(key);
                list.add(JSON.parseObject(vostr,StrategyStatisVO.class));
            }
        }
        return list;
    }

}
